/*************************************************************
   Copyright(C) 2017 by WuIslet
   All rights reserved.
   
   ControlItemDrawer.cs
   UnityFramework
   
   Created by WuIslet on 2020-11-03.
   
*************************************************************/

using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using Object = UnityEngine.Object;

public class ControlItemDrawer
{
    private UIEditorData            _container;
    private CtrlItemData            _itemData;
    private int                     _controlTypeIdx = 0;
    private bool                    _foldout = false;
    private string[]                _list;
    private FilterDropdown          _dropdownMenu;

    public ControlItemDrawer(UIEditorData container, CtrlItemData item, GameObject root)
    {
        _container = container;
        _itemData = item;
        var target = _itemData.GetTargets(root, onlyGO: true) as GameObject;
        _list = GetAllTypeName(target);
        _dropdownMenu = new FilterDropdown(_list, onDropdownClick, onDropdownCompare);
    }

    public CtrlItemData getData()
    {
        return _itemData;
    }

    public bool checkPath(string path)
    {
        return _itemData.targetsPath == path;
    }

    public string[] GetAllTypeName(GameObject target)
    {
        var list = UIControlDataType.GetList();
        var allTypeNames = new List<string>(list.Count);
        for (int i = 0; i < list.Count; ++i)
        {
            if (list[i].unityType == typeof(GameObject) || target == null || target.GetComponent(list[i].unityType))
            {
                allTypeNames.Add(list[i].name);
            }
        }
        return allTypeNames.ToArray();
    }

    public bool Draw(GameObject root, bool isDebug)
    {
        var obj = _itemData.GetTargets(root);
        Rect rect = EditorGUILayout.BeginVertical(GUI.skin.box);
        EditorGUILayout.BeginHorizontal();
        {
            if (_itemData.isList)
            {
                EditorGUILayout.LabelField("#" + _itemData.index + " 变量组", GUILayout.Width(60f));
                _itemData.listName = EditorToolsUtils.FormatProgramName(EditorGUILayout.TextField(_itemData.listName));
            }
            else
            {
                EditorGUILayout.LabelField("#" + _itemData.index + " 变量", GUILayout.Width(60f));
                _itemData.name = EditorToolsUtils.FormatProgramName(EditorGUILayout.TextField(_itemData.name));
            }
            EditorGUI.BeginChangeCheck();
            _itemData.isList = EditorToolsUtils.DrawToggleTag(_itemData.isList, "组",
                Color.white, Color.black, Color.black, Color.white);
            if (EditorGUI.EndChangeCheck())
            {
                if (_itemData.isList)
                {
                    if (string.IsNullOrEmpty(_itemData.listName))
                        _itemData.listName = EditorToolsUtils.FormatProgramName(_itemData.GetTargets(root).name);
                }
            }

            _itemData.isNotGeneratorCode = EditorToolsUtils.DrawToggleTag(_itemData.isNotGeneratorCode, "程",
                Color.white, Color.black, Color.black, Color.white);

            EditorGUILayout.Space();
            if (string.IsNullOrEmpty(_container.searchText))
            {
                if (GUILayout.Button("+"))
                {
                    _container.AddControlAfter(this);
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndVertical();
                    return false;
                }

                if (GUILayout.Button("-"))
                {
                    _container.RemoveControl(this);
                    EditorGUILayout.EndHorizontal();
                    EditorGUILayout.EndVertical();
                    return false;
                }
            }
            GUILayout.FlexibleSpace();

            if (obj == null)
            {
                EditorToolsUtils.DrawTextTag("空", Color.blue, Color.black);
            }
            if (obj != null && _itemData.name != obj.name)
            {
                EditorToolsUtils.DrawTextTag("名", Color.yellow, Color.black);
            }
            if (obj != null)
            {
                if (UISceneToolWindow.isUseTagTool)
                {
                    var go = obj as GameObject;
                    if (go == null && obj is Component)
                    {
                        go = (obj as Component).gameObject;
                    }
                    if (go != null && !go.CompareTag("UI_ControlData"))
                    {
                        EditorToolsUtils.DrawTextTag("标", Color.green, Color.black);
                    }
                }
            }
        }
        EditorGUILayout.EndHorizontal();

        if (isDebug)
            EditorGUILayout.TextField(_itemData.targetsPath);

        // 控件列表
        EditorGUILayout.BeginHorizontal();
        {
            EditorGUI.BeginChangeCheck();
            obj = EditorGUILayout.ObjectField(obj, typeof(Object), true, GUILayout.MaxWidth(100f));
            if (EditorGUI.EndChangeCheck())
            {
                if (Application.isPlaying && obj is GameObject)
                {
                    var curSel = obj as GameObject;
                    var rootName = curSel.transform.GetUIRootGameObject();
                    if (rootName != UISceneToolWindow.playingWatchPrefab.name)
                    {
                        obj = null;
                    }
                }

                if (obj == null)
                {
                    _itemData.SetTarget(null, EUIControlDataType.None);
                }
                else
                {
                    GameObject go = null;
                    if (obj is Component co)
                    {
                        go = co.gameObject;
                    }
                    else if (obj is GameObject)
                    {
                        go = obj as GameObject;
                    }

                    _itemData.SetTarget(go, EUIControlDataType.None);

                    if (string.IsNullOrEmpty(_itemData.name))
                        _itemData.name = EditorToolsUtils.FormatProgramName(obj.name);
                }

                var target = _itemData.GetTargets(root, onlyGO: true) as GameObject;
                _list = GetAllTypeName(target);
                _dropdownMenu = new FilterDropdown(_list, onDropdownClick, onDropdownCompare);
            }

            EditorGUILayout.LabelField("变量类型 ", GUILayout.Width(60f));

            if (!string.IsNullOrEmpty(_itemData.type))
            {
                _controlTypeIdx = 0;
                for (int i = 0, imax = _list.Length; i < imax; i++)
                {
                    if (_list[i] == _itemData.type)
                    {
                        _controlTypeIdx = i;
                        break;
                    }
                }
            }

            _dropdownMenu.Draw("", _controlTypeIdx);
        }
        EditorGUILayout.EndHorizontal();

        //if (_itemData.IsHasExtraArg())
        //{
        //    EditorGUILayout.BeginHorizontal();
        //    EditorGUILayout.LabelField("额外参数", GUILayout.Width(60f));
        //    _itemData.arg = EditorToolsUtils.FormatProgramName(EditorGUILayout.TextField(_itemData.arg));
        //    if (_itemData.arg.EndsWith(".lua"))
        //        _itemData.arg = _itemData.arg.Substring(0, _itemData.arg.Length - 4);
        //    _itemData.arg = _itemData.arg.Replace('\\', '/');
        //    EditorGUILayout.EndHorizontal();
        //}

        //EditorGUILayout.BeginHorizontal();
        //EditorGUILayout.LabelField("自定义绑定", GUILayout.Width(60f));
        //_itemData.extraFunc[CtrlItemData.BINDNULLINDEX] = EditorToolsUtils.FormatProgramName(EditorGUILayout.TextField(_itemData.extraFunc[CtrlItemData.BINDNULLINDEX]));
        //_itemData.extraGeneratorFunc[CtrlItemData.BINDNULLINDEX] = !EditorToolsUtils.DrawToggleTag(!_itemData.extraGeneratorFunc[CtrlItemData.BINDNULLINDEX],
        //    "函", Color.white, Color.black, Color.black, Color.white);
        //EditorGUILayout.EndHorizontal();

        //EditorGUILayout.BeginHorizontal();
        //EditorGUILayout.LabelField("绑定类型 ", GUILayout.Width(60f));
        //_foldout = EditorGUILayout.Foldout(_foldout, _foldout ? "收起" : "展开", true);
        //if (!_foldout)
        //{
        //    string InUseTypes = "";
        //    for (int i = 0; i < CtrlItemData.BindAllTypes.Count; ++i)
        //    {
        //        var t = CtrlItemData.BindAllTypes[i];
        //        if (_itemData.GetBindFlag(t))
        //        {
        //            InUseTypes += t.ToString()[0];
        //        }
        //    }

        //    GUILayout.Label(InUseTypes);
        //}
        //EditorGUILayout.EndHorizontal();
        //if (_foldout)
        //{
        //    for (int i = 0; i < CtrlItemData.BindAllTypes.Count; ++i)
        //    {
        //        var t = CtrlItemData.BindAllTypes[i];
        //        if (!CtrlItemData.CheckTypeCanUseBindType(_itemData.type, t))
        //            continue;
                
        //        bool isInUse = _itemData.GetBindFlag(t);
        //        EditorGUILayout.BeginHorizontal();
        //        EditorGUI.BeginChangeCheck();
        //        isInUse = EditorGUILayout.Toggle(t.ToString(), isInUse);
        //        if (EditorGUI.EndChangeCheck())
        //        {
        //            _itemData.SetBindFlag(t, isInUse);
        //        }
        //        _itemData.extraFunc[i] = EditorToolsUtils.FormatProgramName(EditorGUILayout.TextField(_itemData.extraFunc[i]));
        //        _itemData.extraGeneratorFunc[i] = !EditorToolsUtils.DrawToggleTag(!_itemData.extraGeneratorFunc[i],
        //            "函", Color.white, Color.black, Color.black, Color.white);
        //        EditorGUILayout.EndHorizontal();
        //    }
        //}

        EditorGUILayout.EndVertical();
        if (checkPath(UISceneToolWindow.selectionPath))
            GUI.color = new Color(0.0f, 1.0f, 0.0f, 1f);
        GUI.Box(rect, "");
        GUI.color = Color.white;

        return true;
    }

    private void onDropdownClick(int newIndex)
    {
        _controlTypeIdx = newIndex;
        if (!_itemData.ChangeControlsTypeTo(_list[_controlTypeIdx], _container.GetScriptSymbol(), _container.GetRoot()))
            _controlTypeIdx = 0;
    }

    private int onDropdownCompare(AdvancedDropdownItem a, AdvancedDropdownItem b)
    {
        return String.Compare(a.name, b.name, StringComparison.Ordinal);
    }
}